package com.beidouapp.mvc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.beidouapp.common.util.JSONUtils;
import com.beidouapp.common.util.UUIDGenerator;
import com.beidouapp.domain.pojo.PrjProgress;
import com.beidouapp.domain.pojo.PrjProgressSummary;
import com.beidouapp.domain.pojo.Project;
import com.beidouapp.domain.vo.ProjectVo;
import com.beidouapp.et.client.domain.DocumentInfo;
import com.beidouapp.exception.BusinessException;
import com.beidouapp.manager.IMClient;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.service.EmployeeService;
import com.beidouapp.service.EngineerService;
import com.beidouapp.service.OrganizationService;
import com.beidouapp.service.ProjectService;
import com.beidouapp.service.UserService;
import com.beidouapp.translator.TranslatorManager;

/**
 *  项目管理{论坛同步用户/咨询客户}
 */
@Controller
@RequestMapping(value = "/project")
public class ProjectController {

    private Logger logger = LoggerFactory.getLogger(ProjectController.class);

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private TranslatorManager translatorManager;
    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private ProjectService projectService;
    @Autowired
	private IMClient imClient;
    @Autowired
    EngineerService engineerService;
    
    final int MAX_FILE_SIZE=10485760;//10M
    /**
     *  跳转到用户列表页面
     *  
     */
    @RequestMapping(value = "/manage/page/list", method = RequestMethod.GET)
    public ModelAndView forward2ManagePage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        view.setViewName("project/project_list");
        return view;
    }


    @RequestMapping(value = "/analysis/page/list", method = RequestMethod.GET)
    public ModelAndView forward2AnalysisPage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        view.setViewName("project/project_analysis");
        return view;
    }

    @RequestMapping(value = "/findPrjProgress/{projid}", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<PrjProgress> findPrjProgress(@PathVariable String projid){
        //findPrjProgressByMap
        try{
            List<PrjProgress> progress =  projectService.findPrjProgressByMap(projid);
            
            return ReturnDataInfo.createSuccessfulExecuteResults(translatorManager.translate(progress));
        } catch (Exception ex) {
            logger.error("获取项目列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }


    @RequestMapping(value = "/listPrjProgressSummary", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<PrjProgressSummary>   listPrjProgressSummary(){
        try{
            List<PrjProgressSummary>  datas=projectService.listPrjProgressSummary();
            Map<String, Object>  totalMap=  engineerService.getDistributeTotal();
            Object obj=totalMap.get("PROJECT_TOTAL");
            Long projectTotal=(Long) (obj==null?0:obj);
            datas=this.translatorManager.translate(datas);
            ReturnDataInfo<PrjProgressSummary>  lkiDataInfo=ReturnDataInfo.createSuccessfulExecuteResults(datas);
            lkiDataInfo.setTotalcount(projectTotal);
            return lkiDataInfo;
        } catch (Exception ex) {
            logger.error("项目分析列表获取异常", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<Project> listProject(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
           long startTime=System.currentTimeMillis();
           List<Project> projects = projectService.findProjectByMap(paramters, offset, limit);
           Project pro=null;
           String offLineMan="";
           String onlineLineMan="";
           if(null!=projects && projects.size()!=0){
        	   Project project=null;
    		   for(int i=0,k=projects.size();i<k;i++){
    			   project=projects.get(i);
            	   if(StringUtils.isBlank(project.getName())){
            		   project.setName(project.getUsername());
            	   }
            	   pro = projectService.getOnAndOffLineMan(project);
            	   if(null!=pro){
            		   offLineMan=pro.getOfflineMan();
            		   if(StringUtils.isBlank(offLineMan)){
            			   offLineMan=pro.getOfflineUserName();
            		   }
                       onlineLineMan=pro.getOnlineMan();
                       if(StringUtils.isBlank(onlineLineMan)){
                    	   onlineLineMan=pro.getOnlineUserName();   }
            	   }
            	   project.setOfflineMan(offLineMan);
        		   project.setOnlineMan(onlineLineMan);
               } 
           }
          
          Integer totalCount = projectService.findProjectCountByMap(paramters);
          long endTime=System.currentTimeMillis();
          logger.info("查询项目列表耗时： "+(endTime-startTime)+" ms");
          return ReturnDataInfo.createSuccessfulExecuteResults(projects, offset, limit, totalCount.longValue());
        } catch (Exception ex) {
            logger.error("获取项目列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }


    /**
     *  
     *  //跳转到新增项目页面
     *  
     */
    @RequestMapping(value = "/page/add", method = RequestMethod.GET)
    public ModelAndView addEmpPage(HttpSession session) {
        ModelAndView view = new ModelAndView();

        view.setViewName("project/project_add");
        return view;
    }
    

    @RequestMapping(value = "/page/projectStatus/{projectId}", method = RequestMethod.GET)
    public ModelAndView projectStatus(HttpSession session,@PathVariable String projectId) {
        ModelAndView view = new ModelAndView();
        if(StringUtils.isBlank(projectId)){
        	  view.setViewName("500");
        }else{
        	  view.setViewName("project/project_status");
        }
        view.addObject("projectId", projectId);
        return view;
    }
    
    /**
     * 
     * 工程师修改页面
     * 
     */
    @RequestMapping(value = "/page/edit/{id}", method = RequestMethod.GET)
    public ModelAndView modifyMemberPage(HttpSession session, @PathVariable String id) {
        ModelAndView view = new ModelAndView();
        ProjectVo projectVo=projectService.getProjectVoById(id);
        JSONObject obj=JSONUtils.convert2Obj(projectVo);
        System.out.println("编辑项目页面： "+obj.toString());
        
        view.addObject("project",JSONArray.fromObject(projectVo) );
        view.setViewName("project/project_edit");
        return view;
    }
    
    /**
     *  
     *  显示项目详细页面
     *  
     */
    @RequestMapping(value = "/page/showProjectDetail/{id}", method = RequestMethod.GET)
    public ModelAndView showProjectDetail(HttpSession session, @PathVariable String id) {
        ModelAndView view = new ModelAndView();
        ProjectVo projectVo=projectService.getProjectVoById(id);
        JSONObject obj=JSONUtils.convert2Obj(projectVo);
        logger.info("项目详细页面： \n"+obj.toString());
        view.addObject("project",JSONArray.fromObject(projectVo) );
        view.setViewName("project/project_detail");
        return view;
    }



    @RequestMapping(value = "/getProjectById/{id}", method = RequestMethod.GET)
    public @ResponseBody Project getProjectById(HttpSession session, @PathVariable String id) {
        return projectService.getProjectVoById(id);

    }
    //新增或修改项目
    @RequestMapping(value = "/saveOrgUpdateProject", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> saveOrgUpdateProject(HttpSession session, HttpServletRequest request,@RequestBody Project project) {
        try {
            
        	Integer id= 	projectService.saveOrgUpdateProject(project);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(String.valueOf(id));
        } catch (Exception ex) {
        	logger.error("错误："+ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
    
    /**
     *  新增或修改项目进度项
     * @throws IOException 
     *  
     */
    @SuppressWarnings("finally")
	@RequestMapping(value = "/saveOrgUpdatePrjProgress", method = RequestMethod.POST)
    public
    void saveOrgUpdatePrjProgress(HttpSession session, HttpServletResponse response,HttpServletRequest request, @RequestParam MultipartFile attachment) throws IOException {
    	Map<String, String> pMap=new HashMap<String, String>();
        try {
        	response.setContentType("text/html;chartset=UTF-8");
        	response.setCharacterEncoding("UTF-8"); 
        	PrjProgress prjProgress =new PrjProgress();
        	Map map = request.getParameterMap();
        	 ConvertUtils.register(new DateLocaleConverter(Locale.CHINESE), Date.class);  
        	BeanUtils.populate(prjProgress, map);
            if(null!=attachment && attachment.getSize()!=0 && "500000-0002".equals(prjProgress.getProgressTypeCode())){//只有是合同附件的code才能上传
            	if(attachment.getSize()>MAX_FILE_SIZE){
            		 throw new BusinessException("文件太大，请重新选择 ");
            	}
    				String fileLocation=request.getSession().getServletContext().getRealPath("/")+attachment.getOriginalFilename();
    		    	InputStream inputStream=attachment.getInputStream();
    		    	FileOutputStream output=new FileOutputStream(fileLocation);
    		    	try{
    		    		int len=0;
    			    	byte [] bs=new byte[1024];
    			    	while((len=inputStream.read(bs))!=-1){
    			    		output.write(bs, 0, len);
    			    	}
    			    	DocumentInfo  	doc=imClient.upload(fileLocation);
    			    	if(null!=doc){
    			    		prjProgress.setAttachmentName(doc.getFileName());
    			    		String path=doc.getFileId();
    			    		logger.info("文件路径："+path);
    			    		prjProgress.setAttachmentPath(path);
    			    		prjProgress.setAttachmentIp(doc.getIp());
    			    		prjProgress.setAttachmentPort(doc.getPort());
    			    	}else{
    			    		logger.error("上传合同附件失败。。。");
    			    	}
    		    	}catch(Exception ex){
    		    		logger.error("IM上传合同附件失败。。。"+ex.getMessage());
    		    		throw ex;
    		    	}finally{
    		    		inputStream.close();
    		    		output.close();
    		    		new File(fileLocation).delete();
    		    	}
            } 
        	String	pId=projectService.saveOrgUpdatePrjProgress(prjProgress);
        	logger.info("编辑项目进度ID:"+pId);
        	 pMap.put("pId", pId);
        	 pMap.put("message", "success");
        } catch (Exception ex) {
        	String msg=ex.getMessage();
        	if(msg.indexOf("project_pcode")>=0){
        		msg="数据已经存在,请不要重复提交";
        	}
        	 pMap.put("pId", "");
        	 pMap.put("message", msg);
        	 logger.error("上传文件出错："+msg);
        }finally{
			response.getWriter().write(JSONObject.fromObject(pMap).toString());
        }
    }
    
    /**
     *  
     *  下载附件
     * @throws IOException 
     *  
     */
    @SuppressWarnings("finally")
	@RequestMapping(value = "/downloadAttachment/{id}", method = RequestMethod.GET)
    public  @ResponseBody ReturnDataInfo<String>  downloadAttachment(HttpSession session, @PathVariable String id,HttpServletRequest request,HttpServletResponse response)   {
    	PrjProgress	prjProgress=projectService.getPrjProgressById(id);
    	String errorMsg="";
    	String downLoadFile="";
    	javax.servlet.ServletOutputStream out =null;
    	try {
    	if(null==prjProgress){
    		throw new BusinessException("项目进度对象不存在！");
    	}
    	DocumentInfo documentInfo=new DocumentInfo();
    	String tmpFile=UUIDGenerator.get32UUID();
    	String fileLocation=request.getSession().getServletContext().getRealPath("/");
    	downLoadFile=fileLocation+tmpFile;
    	System.out.println(fileLocation);
    	documentInfo.setIp(prjProgress.getAttachmentIp());
    	documentInfo.setPort(prjProgress.getAttachmentPort());
		documentInfo.setFileId(prjProgress.getAttachmentPath());
		
		
		String oldFileName=prjProgress.getAttachmentName();
		if(StringUtils.isBlank(oldFileName)){
        	throw new BusinessException("当前下载文件不存在！");
        }
		
        imClient.download(documentInfo, downLoadFile);
        InputStream is = new FileInputStream(downLoadFile);
        out= response.getOutputStream();
        response.reset();  
        oldFileName=tmpFile+oldFileName.substring(oldFileName.lastIndexOf("."));
        response.setHeader("Content-Disposition", "attachment; filename=" +oldFileName);
        response.setContentType("multipart/form-data");  
        byte[] content = new byte[1024];
        int length = 0;
        while ((length = is.read(content)) != -1) {
        out.write(content, 0, length);
        }
        out.write(content);
        out.flush();
        out.close();
        is.close();
		} catch (Exception e) {
			 logger.error("下载文件出错！",e);
			 errorMsg=e.getMessage();
		}finally{
			new File(downLoadFile).delete();
			if(null!=out){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(StringUtils.isNotBlank(errorMsg)){
				return ReturnDataInfo.createFailedExecuteResult(errorMsg);
			}
			return null;
		}
    }
    
    /**
     * 
     * 获取项目进度对象
     * 
     */
    @RequestMapping(value = "/getPrjProgressById/{id}", method = RequestMethod.GET)
    public @ResponseBody ReturnDataInfo<PrjProgress> getPrjProgressById(HttpSession session, @PathVariable String id) {
    	PrjProgress	prjProgress=null;
    	try {
    		prjProgress=projectService.getPrjProgressById(id);
		} catch (Exception e) {
			return  ReturnDataInfo.createFailedExecuteResult(e.getMessage());
		}
    	return  ReturnDataInfo.createSuccessfulSingleExecuteResult(prjProgress);
    }

}
